import type {
  IMatchConfig,
  IMatchingRule,
  Operator,
  OperatorOption,
} from './types'
import { getMatchConfig } from './config'

/**
 * 获取运算符对应的模板
 * @param operator 运算符
 */
export function getOperatorTemplate(
  operatorOptions: OperatorOption[],
  operator: Operator,
) {
  return operatorOptions.find(item => item.value === operator)!
    .template as string
}

/**
 * 处理规则值
 * @param operator
 * @param value
 */
export function handleRuleValue(
  operator: Operator,
  value: string | number | string[] | number[],
) {
  const format = (val: string) =>
    val.trim().replaceAll(`"`, `\\"`).replaceAll(`'`, `\\'`)

  let arr: string[] = []
  if (!Array.isArray(value)) {
    arr = [value.toString()]
  } else {
    arr = value.map(item => item.toString())
  }

  if (operator !== 'in' && operator !== 'not_in') {
    return `"${format(arr.join())}"`
  }

  return `{"${arr.join(`" "`)}"}`
}

/**
 * 获取字段配置
 * @param field
 * @returns
 */
export function getFieldConfig(field: string, configs?: IMatchConfig[]) {
  if (!configs) {
    configs = getMatchConfig()
  }
  return configs.find(config => config.value === field)
}

export async function formatMatchingRules(rules: IMatchingRule[]) {
  function getVal(
    arr: LabelValue<string | number>[],
    value: string | number,
    single?: boolean,
  ) {
    return arr?.find(item => (single ? item : item.value) === value)
  }

  return Promise.all(
    rules.map(async (rule) => {
      const ruleConfig = getFieldConfig(rule.field)!
      const operator = getVal(ruleConfig?.operatorOptions, rule.operator)

      const obj = {
        field: ruleConfig?.label,
        origin_field: rule.field,
        operator: operator?.label,
        origin_operator: rule.operator,
        value: '',
      }
      if (
        ['country', 'continent', 'method', 'http_version'].includes(
          ruleConfig?.value,
        )
      ) {
        const arr = [] as string[]

        ruleConfig?.field?.options?.forEach((item) => {
          const data = Array.isArray(rule?.value)
            ? getVal(rule?.value, item.field, true)
            : rule?.value
          const res = item.field === data ? item.show_name : ''
          if (res) {
            arr.push(res)
          }
          obj.value = arr.join(',')
        })
      } else {
        obj.value = rule.value as string
      }
      return obj
    }),
  )
}
/**
 * 从表单数据中获取字段值
 *
 * @param form 表单数据对象
 * @param type 字段类型，默认为 'field'
 * @param operator 操作符，默认为 'operator'
 * @returns 返回字段值对象
 */
export function getFieldValue(
  form: any,
  type: string = 'field',
  operator: string = 'operator',
) {
  const fieldConfig = getFieldConfig(form[type], getMatchConfig())
  const res = fieldConfig?.operatorOptions!.find(
    (item: any) => item.value === form[operator],
  )
  return res
}
export function getSecondAllowValue(
  form: any,
  type: string = 'field',
  operator: string,
) {
  const fieldConfig = getFieldConfig(form[type], getMatchConfig())
  const res = fieldConfig?.operatorOptions!.find((item: any) => {
    return item.value === operator
  })
  return (
    res?.allowed_values.map((item: any) => ({
      label: item.show_name,
      value: item.field,
    })) ?? []
  )
}
